package com.qifenqian.turbot.module.ui.loginetc

import android.Manifest
import android.content.Context
import android.content.Intent
import com.bumptech.glide.Glide
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.config.Constant
import com.qifenqian.turbot.config.Constant.TAG_ACTIVITY_COLLECTOR_REGISTER
import com.qifenqian.turbot.module.contract.AccountContract
import com.qifenqian.turbot.module.dialog.ExampleImageDialog
import com.qifenqian.turbot.module.dialog.TYPE_EXAMPLE_ID_CARD
import com.qifenqian.turbot.module.entity.response.UploadEntity
import com.qifenqian.turbot.module.presenter.AccountPresenter
import com.qifenqian.turbot.util.ActivityCollector
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.util.MyGlideEngine
import com.qifenqian.turbot.util.SendSmsUtil
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.activity_identity_verify.*
import kotlinx.android.synthetic.main.layout_complete_bar.*
import org.jetbrains.anko.toast

private const val COUNTDOWN_TIME: Long = 60
private const val REQUEST_IMAGE_CHOOSE_FRONT = 0x15
private const val REQUEST_IMAGE_CHOOSE_BACK = 0x124

/**
 * @author H
 * @createDate 2018/12/17 14:10
 * @description 注册时候的资质认证1
 * @see
 * @since
 */
class IdentityVerifyActivity : BaseActivity<AccountPresenter, AccountContract.View>(), AccountContract.View {

    override fun sendSmsCodeResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            SendSmsUtil.beginCountdown(this, Constant.COUNTDOWN_TIME, btn_identity_verify_get_code)
            toast("获取验证码成功")
        }
    }

    override fun identityVerifyFirstResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            IdentityVerifyPhotoActivity.startThis(this, mUserCode)
        }
    }

    companion object {
        fun startThis(context: Context, userCode: String) {
            val intent = Intent(context, IdentityVerifyActivity::class.java)
            intent.putExtra("userCode", userCode)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.activity_identity_verify
    }

    override fun bindPresenter(): AccountPresenter? {
        return AccountPresenter(this, this)
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this, TAG_ACTIVITY_COLLECTOR_REGISTER)
    }

    private var mUserCode: String = ""
    override fun initial() {
        ActivityCollector.addActivity(this, TAG_ACTIVITY_COLLECTOR_REGISTER)
        mUserCode = intent.getStringExtra("userCode")
        btn_identity_verify_example.setOnClickListener {
            // 2018/12/17 查看身份证示例
            ExampleImageDialog.newInstance(TYPE_EXAMPLE_ID_CARD).show(this, "")
        }
        iv_complete_bar_1.setImageResource(R.mipmap.ic_verify_default)
        iv_complete_bar_2.setImageResource(R.drawable.shape_circle)
        iv_complete_bar_3.setImageResource(R.drawable.shape_circle)
        iv_identity_verify_front.setOnClickListener {
            RxPermissions(this)
                    .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA)
                    .subscribe { it1 ->
                        if (it1) {
                            chooseImage(REQUEST_IMAGE_CHOOSE_FRONT)
                        } else {
                            toast("没有权限")
                        }
                    }
        }
        iv_identity_verify_back.setOnClickListener {
            RxPermissions(this)
                    .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA)
                    .subscribe { it1 ->
                        if (it1) {
                            chooseImage(REQUEST_IMAGE_CHOOSE_BACK)
                        } else {
                            toast("没有权限")
                        }
                    }
        }
        btn_identity_verify_get_code.setOnClickListener {
            if (et_identity_verify_phone_number.text.toString().isBlank()) {
                toast("请输入银行预留手机号码")
                return@setOnClickListener
            }
            SendSmsUtil.beginCountdown(this, COUNTDOWN_TIME, btn_identity_verify_get_code)
            // TODO: 2018/12/17 16:09 发送验证码 ----->
        }
        btn_identity_verify_next.setOnClickListener {
            Lcat.i("身份证正面tag", iv_identity_verify_front.tag)
            Lcat.i("身份证反面tag", iv_identity_verify_back.tag)
            if (iv_identity_verify_front.tag == "defaultFrontImage") {
                toast("请上传身份证正面照片")
                return@setOnClickListener
            }
            if (iv_identity_verify_back.tag == "defaultBackImage") {
                toast("请上传身份证反面照片")
                return@setOnClickListener
            }
            if (et_identity_verify_bank_card_number.text.toString().isBlank()) {
                toast("请输入银行卡号")
                return@setOnClickListener
            }
            if (et_identity_verify_bank_card_name.text.toString().isBlank()) {
                toast("请输入开户银行")
                return@setOnClickListener
            }
            if (et_identity_verify_phone_number.text.toString().isBlank()) {
                toast("请输入银行预留手机号码")
                return@setOnClickListener
            }
            if (et_identity_verify_sms_code.text.toString().isBlank()) {
                toast("请输入验证码")
                return@setOnClickListener
            }
            // TODO: 2018/12/17 16:20 下一步 ----->
            mPresenter!!.identityVerifyFirst(mUserCode, mFrontUrl, mBackUrl,
                    et_identity_verify_bank_card_number.text.toString(), et_identity_verify_bank_card_name.text.toString(),
                    et_identity_verify_phone_number.text.toString(), et_identity_verify_sms_code.text.toString())
            // TODO: 2018/12/25 15:03 移除 ----->
            IdentityVerifyPhotoActivity.startThis(this, mUserCode)
        }
    }

    private fun chooseImage(requestCode: Int) {
        Matisse.from(this@IdentityVerifyActivity)
                .choose(MimeType.ofImage())
                .countable(false)
                .capture(true)
                .captureStrategy(CaptureStrategy(true, Constant.AUTHORITY))
                .maxSelectable(1)
                .originalEnable(true)
                .maxOriginalSize(10)
                .imageEngine(MyGlideEngine())
                .forResult(requestCode)
    }

    private var mFrontUrl: String = ""
    private var mBackUrl: String = ""

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CHOOSE_FRONT && resultCode == RESULT_OK) {
//            Glide.with(this)
//                    .load(Matisse.obtainPathResult(data)[0])
//                    .into(iv_identity_verify_front)
//            iv_identity_verify_front.tag = "front_ok"
            mPresenter!!.uploadFile(REQUEST_IMAGE_CHOOSE_FRONT, Matisse.obtainPathResult(data)[0])
        }
        if (requestCode == REQUEST_IMAGE_CHOOSE_BACK && resultCode == RESULT_OK) {
//            Glide.with(this)
//                    .load(Matisse.obtainPathResult(data)[0])
//                    .into(iv_identity_verify_back)
//            iv_identity_verify_back.tag = "back_ok"
            mPresenter!!.uploadFile(REQUEST_IMAGE_CHOOSE_BACK, Matisse.obtainPathResult(data)[0])
        }
    }

    override fun uploadFileResult(isSuccess: Boolean, code: Int, msg: String?, requestCode: Int, uploadEntity: UploadEntity?) {
        if (isSuccess) {
            when (requestCode) {
                REQUEST_IMAGE_CHOOSE_FRONT -> {
                    mFrontUrl = uploadEntity!!.url
                    Glide.with(this)
                            .load(mFrontUrl)
                            .into(iv_identity_verify_front)
                    iv_identity_verify_front.tag = "front_ok"
                }
                REQUEST_IMAGE_CHOOSE_BACK  -> {
                    mBackUrl = uploadEntity!!.url
                    Glide.with(this)
                            .load(mBackUrl)
                            .into(iv_identity_verify_back)
                    iv_identity_verify_back.tag = "back_ok"
                }
            }
        }
        toast(msg!!)
    }
}